GApp.AreasConfiguration = {
    list: [],
    url: '/?url=configAreas/areas'
};

(function (P) {
    
///////////////////////////////////////////////////////////////////////////////
// AREA
///////////////////////////////////////////////////////////////////////////////

    P.getArea = function (id) {
        var area = null;
        $.each(P.list, function (i, v) {
           if (v.id === id) {
               area = P.list[i];
           } 
        });
        return area;
    },
    
    P.updateTableArea = function (url, doneCallback) {
         var idScheme = $('#idScheme').val ();
         
         $.ajax ({
            type: 'get',
            url: GApp.baseURL + url,
            data: { 'idScheme': idScheme }
        })
        .done (function (data) {
            var tmp = [];
            var json = JSON.parse (data);
            
            P.list.length = 0;
            
            $('#dataTables-areas > tbody').html ('');
            $.each(json, function (i, v) {
                tmp.push ('<tr class="odd gradeX">');
                tmp.push ('<td align="center">');
                tmp.push ('<a href="#" onclick="GApp.AreasConfiguration.viewArea (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-gear fa-lg"></i></a> '); 
                tmp.push ('<a href="#" onclick="GApp.AreasConfiguration.modifyArea (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-pencil-square fa-lg"></i></a> '); 
                tmp.push ('<a href="#" onclick="GApp.AreasConfiguration.removeArea (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-minus-square fa-lg"></i></a>');
                tmp.push ('</td>');
                tmp.push ('<td>' + v.name + '</td>');
                tmp.push ('<td>' + v.order + '</td>');
                tmp.push ('</tr>');
                P.list.push (v);
            });
            
            $('#dataTables-areas > tbody').html (tmp.join (''));
            
            if (doneCallback) {
                doneCallback.call (this);
            }
        })
        .fail (function () {
            console.log ('ERROR: updateTableArea');
        });
    },
    
    P.sendArea = function (data, okCallback, errorCallback) {
        var url = ($('#areaIdForm').val () !== '') ? 'modifyArea' : 'addArea';
        var idScheme = $('#idScheme').val ();

        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configAreas/' + url,
            data: {
                idScheme: idScheme,
                name: data.name,
                order: data.order,
                id: data.id
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.sendRemoveArea = function (data, okCallback, errorCallback) {        
        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configAreas/removeArea',
            data: {
                id: data.id
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.validateAndCommitModal = function () {
        var errors = 0;
        var area = {
            id: $('#areaIdForm').val () || null,
            name: $('#areaNameForm').val () || null,
            order: $('#areaOrderForm').val ()
        };

        if (!area.name || area.name.length == 0) {
            $('#areaNameForm').parent ().addClass ('has-error');
            errors++;
        }
        else {
            $('#areaNameForm').parent ().removeClass ('has-error');
        }

        if (errors === 0) {
             P.sendArea (area, 
                 function () {
                    // OK
                    $('#areaModalDlg').modal ('hide');
                    P.updateTableArea (P.url);
                 },
                 function () {
                    // Error
                    console.log  ('Error: validateAndCommitModal');
                 }
             );
        }
    },
    
    P.confirmFormArea = function (area) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>¿Quieres eliminar el área seleccionada?</label>');
        form.push ('</div>');
        
        $('#areaModalLabel').text ('Eliminar área');
        $('#areaAcceptModalDlg').on ('click', function () {
           P.sendRemoveArea(area, 
                 function () {
                    // OK
                    $('#areaModalDlg').modal ('hide');
                    P.updateTableArea (P.url);
                 },
                 function () {
                    // Error
                    console.log  ('Error: confirmFormArea');
                 }
            );
        });
        
        $('#areaModalBody').html (form.join (''));
        $('#areaModalDlg').modal ();
        $('#areaModalDlg').on ('hidden.bs.modal', function () {
            $('#areaAcceptModalDlg').off ('click');
            $('#areaModalDlg').off ('hidden.bs.modal');
        });
        
        if (area) {
            $('#areaIdForm').val (area.id);
        }
        
        return false;
    },
    
    P.showFormArea = function (title, area) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>Nombre</label>');
        form.push ('<input class="form-control" placeholder="Nombre del área" id="areaNameForm">');
        form.push ('</div>');
        form.push ('<div class="form-group">');
        form.push ('<label>Orden</label>');
        form.push ('<input class="form-control" placeholder="Orden" id="areaOrderForm">');
        form.push ('<input type="hidden" id="areaIdForm">');
        form.push ('</div>');
        
        $('#areaModalLabel').text (title);
        $('#areaAcceptModalDlg').on ('click', function () {
           P.validateAndCommitModal ();
        });
        
        $('#areaModalBody').html (form.join (''));
        $('#areaModalDlg').modal ();
        $('#areaModalDlg').on ('hidden.bs.modal', function () {
            $('#areaAcceptModalDlg').off ('click');
            $('#areaModalDlg').off ('hidden.bs.modal');
        });
        
        if (area) {
            $('#areaNameForm').val (area.name);
            $('#areaOrderForm').val (area.order);
            $('#areaIdForm').val (area.id);
        }
        
        return false;
    },

    P.newArea = function () {        
        return P.showFormArea ('Nueva área');
    },

    P.modifyArea = function (areaId) {
        return P.showFormArea ('Modificar área', P.getArea (areaId));
    },
    
    P.removeArea = function (areaId) {
        return P.confirmFormArea (P.getArea (areaId));
    },
    
    P.viewArea = function (areaId) {
        var idScheme = $('#idScheme').val ();
        window.location = GApp.baseURL + '?url=configArea&idScheme=' + idScheme + '&id=' + areaId;
    }
} (GApp.AreasConfiguration));

if (document.URL.indexOf ('url=configAreas&id') > 0) {
    GApp.Helper.createWaitDialog ('waitingModal');
    
    $(document).ready (function () {
        GApp.Helper.showPleaseWait ();
        GApp.AreasConfiguration.updateTableArea (GApp.AreasConfiguration.url, function () {
            GApp.Helper.hidePleaseWait ();
        });
    });
}
